package basic;

public class CloneDemo {

	public static void main(String[] args) throws CloneNotSupportedException {
		t2();
	}
	public static void t1() throws CloneNotSupportedException{
		CloneA ca=new CloneA();
		Child child=new Child();
		child.setName("jiejie");
		ca.child=child;
		CloneA cca=(CloneA)ca.clone();
		System.out.println(cca.child.getName());	
	}
	public static void t2() throws CloneNotSupportedException{
		CloneB cb=new CloneB();
		Child child=new Child();
		child.setName("noclone");
		cb.child=child;
		System.out.println(cb.child.getName());
		CloneB ccb=(CloneB) cb.clone();
		ccb.child.setName("clone");
		System.out.println(cb.child.getName());
		System.out.println(ccb.child.getName());
	}

}
class CloneA implements Cloneable{
	//浅拷贝,就是clone一个引用,所指的内存地址是一样的
	public Integer count;
	public Child child;
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
	
}
/**
 * 需要重写clone方法，不仅仅只调用父类的方法，还需调用属性的clone方法
•做到了原对象与克隆对象之间100%数据分离
•如果是对象存在引用类型的属性，建议使用深拷贝
•深拷贝比浅拷贝要更加耗时，效率更低

 * @author jieji
 *
 */
class CloneB implements Cloneable{
	//深拷贝,所指的内存地址不一样
	public Integer count;
	public Child child;
	@Override
	protected Object clone() throws CloneNotSupportedException {
		CloneB cb=(CloneB)super.clone();
		cb.child=(Child) child.clone();
		return cb;
	}
	
}
class Child implements Cloneable{
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}
